package com.thinkingcoder.tcregistry.cluster;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.thinkingcoder.tcregistry.http.HttpInvoker;
import com.thinkingcoder.tcregistry.service.TcRegistryService;

import lombok.extern.slf4j.Slf4j;

/**
 * check health for servers.
 */
@Slf4j
public class ServerHealth {

    final Cluster cluster;

    public ServerHealth(Cluster cluster) {
        this.cluster = cluster;
    }

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    long timeout = 5_000;

    public void checkServerHealth() {
        executor.scheduleAtFixedRate(() -> {
            try {
                // 1.更新服务器状态
                updateServers();
                // 2.选主
                doElect();
                // 3.快照同步
                syncSnapshotFromLeader();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 0, timeout, TimeUnit.MILLISECONDS);
    }

    private void updateServers() {
        List<Server> servers = cluster.getServers();
        servers.stream().parallel().forEach(server -> {
            try {
                if (server.equals(cluster.self())) {
                    return;
                }

                Server serverInfo = HttpInvoker.httpGet(server.getUrl() + "/info", Server.class);
                log.debug(" ===>>> health check success for " + serverInfo);
                if (serverInfo != null) {
                    server.setStatus(true);
                    server.setLeader(serverInfo.isLeader());
                    server.setVersion(serverInfo.getVersion());
                }
            } catch (Exception e) {
                log.debug(" ===>>> health check failed for " + server);
                server.setStatus(false);
                server.setLeader(false);
            }
        });
    }

    private void doElect() {
        new Election().electLeader(cluster.getServers());
    }

    private void syncSnapshotFromLeader() {
        Server self = cluster.self();
        Server leader = cluster.leader();
        log.debug(" ===>>> leader version: " + leader.getVersion());
        if (!self.isLeader() && self.getVersion() < leader.getVersion()) {
            log.debug(" ===>>> sync snapshot from leader:" + leader);
            Snapshot snapshot = HttpInvoker.httpGet(leader.getUrl() + "/snapshot", Snapshot.class);
            log.debug(" ===>>> sync and restore snapshot:" + snapshot);
            TcRegistryService.restore(snapshot);
        }
    }
}
